package com.souku.finance.application.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.souku.finance.application.R;
import com.souku.finance.application.base.BaseActivity;
import com.souku.finance.application.utils.ToastUtil;

import java.io.File;

/**
 * Created by Android on 2017/1/18.
 */

public class UpdateActivity extends BaseActivity implements View.OnClickListener {

    protected ImageView ivDelet;
    protected Button btnOk;
    protected TextView filenameTv2;
    protected TextView speedTv2;
    protected ProgressBar progressBar2;
    private int downloadId1;
    private static Activity activity;
    private String llsApkDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_update);
        initView();
        llsApkDir = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "tmpdir1";
        activity = this;
    }

    @Override
    public void internet() {

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_delet) {
            finish();
        } else if (view.getId() == R.id.btn_ok) {
            downloadId1 = createDownloadTask().start();
        }
    }

    private void initView() {
        ivDelet = (ImageView) findViewById(R.id.iv_delet);
        ivDelet.setOnClickListener(UpdateActivity.this);
        btnOk = (Button) findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(UpdateActivity.this);
        filenameTv2 = (TextView) findViewById(R.id.filename_tv_2);
        speedTv2 = (TextView) findViewById(R.id.speed_tv_2);
        progressBar2 = (ProgressBar) findViewById(R.id.progressBar_2);
    }


    private BaseDownloadTask createDownloadTask() {
        final ViewHolder tag;
        final String url;
        boolean isDir;
        url = "http://imtt.dd.qq.com/16891/A87717BF3A5C957BBE1B7630C6592A18.apk";
        tag = new ViewHolder(progressBar2, null, speedTv2, 2);
        isDir = true;
        tag.setFilenameTv(filenameTv2);
        return FileDownloader.getImpl().create(url)
                .setPath(llsApkDir, isDir)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                .setTag(tag)
                .setListener(new FileDownloadSampleListener() {

                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.pending(task, soFarBytes, totalBytes);
                        ((ViewHolder) task.getTag()).updatePending(task);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.progress(task, soFarBytes, totalBytes);
                        ((ViewHolder) task.getTag()).updateProgress(soFarBytes, totalBytes,
                                task.getSpeed());
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        super.error(task, e);
                        ((ViewHolder) task.getTag()).updateError(e, task.getSpeed());
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                        ((ViewHolder) task.getTag()).updateConnected(etag, task.getFilename());
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        super.paused(task, soFarBytes, totalBytes);
                        ((ViewHolder) task.getTag()).updatePaused(task.getSpeed());
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        super.completed(task);
                        ((ViewHolder) task.getTag()).updateCompleted(task);
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        super.warn(task);
                        ((ViewHolder) task.getTag()).updateWarn();
                    }
                });
    }

    private static class ViewHolder {
        private ProgressBar pb;
        private TextView detailTv;
        private TextView speedTv;
        private int position;
        private TextView filenameTv;


        public ViewHolder(final ProgressBar pb, final TextView detailTv, final TextView speedTv, final int position) {
            this.pb = pb;
            this.detailTv = detailTv;
            this.position = position;
            this.speedTv = speedTv;
        }

        public void setFilenameTv(TextView filenameTv) {
            this.filenameTv = filenameTv;
        }

        private void updateSpeed(int speed) {
            speedTv.setText(String.format("%dKB/s", speed));
        }

        public void updateProgress(final int sofar, final int total, final int speed) {
            if (total == -1) {
                // chunked transfer encoding data
                pb.setIndeterminate(true);
            } else {
                pb.setMax(total);
                pb.setProgress(sofar);
            }

            updateSpeed(speed);

            if (detailTv != null) {
                detailTv.setText(String.format("sofar: %d total: %d", sofar, total));
            }
        }

        public void updatePending(BaseDownloadTask task) {
            if (filenameTv != null) {
                filenameTv.setText(task.getFilename());
            }
        }

        public void updatePaused(final int speed) {
            updateSpeed(speed);
            pb.setIndeterminate(false);
        }

        public void updateConnected(String etag, String filename) {
            if (filenameTv != null) {
                filenameTv.setText(filename);
            }
        }

        public void updateWarn() {
            ToastUtil.show("下载中");
            pb.setIndeterminate(false);
        }

        public void updateError(final Throwable ex, final int speed) {
            toast(String.format("error %d %s", position, ex));
            updateSpeed(speed);
            pb.setIndeterminate(false);
            ex.printStackTrace();
        }

        public void updateCompleted(final BaseDownloadTask task) {

            ToastUtil.show("下载完成");

            if (detailTv != null) {
                detailTv.setText(String.format("sofar: %d total: %d",
                        task.getSmallFileSoFarBytes(), task.getSmallFileTotalBytes()));
            }
            updateSpeed(task.getSpeed());
            pb.setIndeterminate(false);
            pb.setMax(task.getSmallFileTotalBytes());
            pb.setProgress(task.getSmallFileSoFarBytes());

            openFile(activity, new File(task.getTargetFilePath()));
        }

        private void toast(final String msg) {
            ToastUtil.show(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileDownloader.getImpl().pause(downloadId1);
    }

    @Override
    public void onBackPressed() {

    }

    private static void openFile(Activity activity, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }
}
